import { PlusOutlined, SettingOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Drawer, message, Modal, Cascader, Row, Col, Space, Tag } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProForm, { ModalForm, ProFormSwitch, ProFormText, ProFormDigit } from '@ant-design/pro-form';
import { useAccess } from 'umi';
import areaOptions from '@/until/cascader-address-options'
import { getSupplierList, deleteSupplier, getSupplierInfo, createSupplier, updateSupplier } from './service'
import type { supplierTableParams } from './data';

const TableList: React.FC = () => {

  const access = useAccess();

  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<supplierTableParams>();

  const [isSupplierVirtual, setSupplierVirtual] = useState(false);

  const searchConfig = {
    resetText: '重置查询',
    searchText: '查询仓库',
  }

  const supplierInfoParams = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '状态',
      width: 100,
      dataIndex: 'status',
      valueType: 'select',
      filters: true,
      onFilter: true,
      hideInSearch: true,
      valueEnum: {
        0: { text: '未启用', status: 'Default', },
        1: { text: '启用中', status: 'Success', },
      },
    },
    {
      title: '地址',
      dataIndex: 'province',
      render: (_, rowData) => {
        return `${rowData.province} ${rowData.city} ${rowData.area} ${rowData.address}`
      }
    },
    {
      title: '容量',
      dataIndex: 'mianji',
      render: (_, rowData) => {
        rowData.mianji && `${rowData.mianji} 立方`
      }
    },
    {
      title: '联系人',
      dataIndex: 'linkman',
      render: (_, rowData) => {
        return `${rowData.linkman} ${rowData.linkphone} `
      }
    },
    {

      title: '仓库所属',
      dataIndex: 'user_name',
    },
    {
      title: '创建日期',
      dataIndex: 'created_at',
    },
    {
      title: '最后更新日期',
      dataIndex: 'updated_at',
    },
  ]

  return (
    <PageContainer>
      <ProTable<supplierTableParams>
        headerTitle="仓库列表"
        loading={false}
        actionRef={actionRef}
        rowKey="id"
        search={searchConfig}
        bordered={true}
        columns={[
          {
            title: '仓库名称',
            dataIndex: 'name',
            render: (dom, rowData) => {
              if (rowData.is_xn === 2) {
                return (
                  <Space><span>{dom}</span> <Tag color={'#108ee9'}>虚拟仓库</Tag></Space>
                );
              } else {
                if (access.getProviderInfo) {
                  return (
                    <a
                      onClick={() => {
                        setCurrentRow(rowData);
                        setShowDetail(true);
                      }}
                    >
                      {dom}
                    </a>
                  );
                } else {
                  return (
                    `${dom}`
                  );
                }
              }
            },
          },
          {
            title: '仓库状态',
            width: 120,
            dataIndex: 'status',
            valueType: 'select',
            filters: true,
            onFilter: true,
            hideInSearch: true,
            valueEnum: {
              0: { text: '未启用', status: 'Default', },
              1: { text: '启用中', status: 'Success', },
            },
          },
          {
            title: '仓库地址',
            hideInSearch: true,
            render: (_, rowData) => {
              return rowData?.province ? `${rowData.province} ${rowData.city} ${rowData.area} ${rowData.address}` : ''
            }
          },
          {
            title: '仓库所属',
            dataIndex: 'user_name',
          },
          {
            title: '更新日期',
            hideInSearch: true,
            dataIndex: 'updated_at',
          },

          {
            title: '操作',
            valueType: 'option',
            render: (dom, rowData) => [
              !!access.updateProvider && rowData.status === 1 && <Button
                key="updateProvider"
                type="primary"
                icon={<SettingOutlined />}
                onClick={() => {
                  setCurrentRow(rowData)
                  setUpdateModalVisible(true)
                }}
              >管理</Button>,
              !!access.deleteProvider && rowData.status === 1 &&
              <Button
                key="deleteProvider"
                type="primary"
                icon={<DeleteOutlined />}
                danger
                onClick={() => {
                  const params = {
                    supplier_id: rowData.id
                  }
                  Modal.confirm({
                    title: `是否停用仓库 ${rowData.name} ？`,
                    icon: <ExclamationCircleOutlined />,
                    content: '若确认，此仓库将设置为停用状态。',
                    okText: '确认停用',
                    okType: 'primary',
                    okButtonProps: {
                      danger: true,
                    },
                    cancelText: '取消',
                    onOk: async () => {
                      const res = await deleteSupplier({ ...params });

                      if (res.code === 200) {
                        message.success('停用成功！')
                        if (actionRef.current) {
                          actionRef.current.reload();
                        }
                      } else {
                        message.error('停用失败,请重试！')
                      }
                    },
                  });
                }}
              >停用</Button>
            ],
          },
        ]}
        pagination={{
          pageSize: 10,
          current: 1
        }}
        toolBarRender={() => [
          !!access.createSupplier &&
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            新增仓库
          </Button>,
        ]}
        request={async (params) => {
          const dataParams = {
            page: params.current,
            limit: params.pageSize,
            name: params.name,
            provider_id: '',
          }
          const res = await getSupplierList({ ...dataParams });
          return {
            data: res.data.list,
            success: res.code === 200,
            total: res.data.total,
          };
        }}
      />

      {
        !!updateModalVisible && (
          <ModalForm
            width={600}
            title="管理仓库"
            visible={updateModalVisible}
            initialValues={{
              supplier_id: currentRow?.id
            }}
            onVisibleChange={setUpdateModalVisible}
            request={async () => {
              const params = {
                supplier_id: currentRow?.id,
              }
              const res = await getSupplierInfo({ ...params });
              const data = res.data.info
              data.areas = [data?.province, data?.city, data?.area]

              setSupplierVirtual(data.is_xn === 2)

              return data;
            }}
            modalProps={
              {
                onCancel: () => {
                  setSupplierVirtual(false)
                }
              }
            }
            onFinish={
              async (value) => {
                const dataValue = {
                  ...value,
                  province: value?.areas && value.areas[0],
                  city: value?.areas && value.areas[1],
                  area: value?.areas && value.areas[2],
                }

                const res = await updateSupplier({ ...dataValue });
                if (res.code === 200) {
                  message.success('修改成功')
                  !!actionRef.current && actionRef.current.reload();
                } else {
                  message.error('修改失败')
                }
                setSupplierVirtual(false)
                setUpdateModalVisible(false)
              }
            }
          >
            <ProFormText
              name="supplier_id"
              hidden
            />
            <Row gutter={12}>
              <Col span="12">
                <ProFormText
                  name="name"
                  label="仓库名称"
                  placeholder="请输入仓库名称"
                  rules={[{ required: true, message: '仓库名称不能为空!' }]}
                />
              </Col>
              {
                !isSupplierVirtual && (
                  <>
                    <Col span="12">
                      <ProForm.Item name="areas" label="仓库所在地" rules={[{ required: true, message: '请选择仓库所在省/市/区!' }]}>
                        <Cascader options={areaOptions} defaultValue={[`${currentRow?.province} / ${currentRow?.city} / ${currentRow?.area} `]} />
                      </ProForm.Item>
                    </Col>
                    <Col span="12">
                      <ProFormText
                        name="address"
                        label="仓库详细地址"
                        placeholder="请输入仓库详细地址"
                        rules={[{ required: true, message: '仓库详细地址不能为空!' }]}
                      />
                    </Col>
                    <Col span="12">
                      <ProFormText
                        name="linkman"
                        label="联系人"
                        placeholder="请输入仓库联系人"
                        rules={[{ required: true, message: '仓库联系人不能为空!' }]}
                      />
                    </Col>
                    <Col span="12">
                      <ProFormText
                        name="linkphone"
                        label="联系方式"
                        placeholder="请输入仓库联系方式"
                        rules={[{ required: true, message: '仓库联系方式不能为空!' }]}
                      />
                    </Col>
                    <Col span="12">
                      <ProFormDigit
                        name="mianji"
                        label="容量（立方）"
                        placeholder="请输入仓库容量"
                      />
                    </Col>
                  </>
                )
              }

            </Row>
          </ModalForm>
        )
      }

      {currentRow?.id && (
        <Drawer
          width={600}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={true}
        >
          <ProDescriptions<supplierTableParams>
            column={1}
            bordered={true}
            size="small"
            title='仓库详情'
            request={async () => {
              const params = {
                supplier_id: currentRow.id,
              }
              const res = await getSupplierInfo({ ...params });
              const data = res.data.info
              data.oil_depot_id = res.data.relations
              return {
                data: data
              };
            }}
            columns={supplierInfoParams as ProDescriptionsItemProps<supplierTableParams>[]}
          />
        </Drawer>
      )}

      {
        !!createModalVisible && (
          <ModalForm
            width={600}
            title={'新增仓库'}
            visible={createModalVisible}
            onVisibleChange={setCreateModalVisible}
            modalProps={
              {
                onCancel: () => {
                  setSupplierVirtual(false)
                }
              }
            }
            onFinish={
              async (value) => {
                const dataValue = {
                  ...value,
                  is_xn: !!value.is_xn_checked ? 2 : 1,
                  province: value?.areas && value.areas[0],
                  city: value?.areas && value.areas[1],
                  area: value?.areas && value.areas[2],
                }

                const res = await createSupplier({ ...dataValue });
                if (res.code === 200) {
                  message.success('添加成功')
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                } else {
                  message.error('添加失败')
                }
                setSupplierVirtual(false)
                setCreateModalVisible(false)
              }
            }
          >
            <Row gutter={12}>
              <Col span="12">
                <ProFormText
                  name="name"
                  label="仓库名称"
                  placeholder="请输入仓库名称"
                  rules={[{ required: true, message: '仓库名称不能为空!' }]}
                />
              </Col>
              <Col span="4" push="1">
                <ProFormSwitch
                  fieldProps={{
                    onChange: function (e) {
                      setSupplierVirtual(e)
                    }
                  }}
                  label="虚拟仓库" name="is_xn_checked" unCheckedChildren="否" checkedChildren="是" initialValue={false} />
              </Col>

              {
                !isSupplierVirtual && (
                  <>
                    <Col span="12">
                      <ProForm.Item name="areas" hidden={!!isSupplierVirtual} label="仓库所在地" rules={[{ required: !isSupplierVirtual, message: '请选择仓库所在省/市/区!' }]}>
                        <Cascader options={areaOptions} />
                      </ProForm.Item>
                    </Col>
                    <Col span="12">
                      <ProFormText
                        name="address"
                        label="详细地址"
                        placeholder="请输入仓库详细地址"
                        rules={[{ required: !isSupplierVirtual, message: '仓库详细地址不能为空!' }]}
                      />
                    </Col>
                    <Col span="12">
                      <ProFormText
                        name="linkman"
                        label="联系人"
                        placeholder="请输入仓库联系人"
                        rules={[{ required: !isSupplierVirtual, message: '仓库联系人不能为空!' }]}
                      />
                    </Col>
                    <Col span="12">
                      <ProFormText
                        hidden={!!isSupplierVirtual}
                        name="linkphone"
                        label="联系方式"
                        placeholder="请输入仓库联系方式"
                        rules={[{ required: !isSupplierVirtual, message: '仓库联系方式不能为空!' }]}
                      />
                    </Col>
                    <Col span="12">
                      <ProFormDigit
                        hidden={!!isSupplierVirtual}
                        name="mianji"
                        label="容量（立方）"
                        placeholder="请输入仓库容量"
                      />
                    </Col>
                  </>
                )
              }
            </Row>
          </ModalForm>
        )
      }

    </PageContainer>
  );
};

export default TableList;
